var mqtt = require('../../utils/mqtt.min');
var client = null;

/* 阿里云MQTT连接参数 */
const clientId = 'i3c6vjLss9C.Wechat|securemode=2,signmethod=hmacsha256,timestamp=1675995798170|';
const username = 'Wechat&i3c6vjLss9C';
const password = 'e1a946abe3597cd2fc7d44bbc564263a8c065010692671234284c0b1ac0a8fee';
const connectUrl = 'wxs://iot-06z00formvsxwnm.mqtt.iothub.aliyuncs.com';
const topic1 = '/i3c6vjLss9C/Wechat/user/control'; // 微信小程序向ESP32发送控制信号

Page({
  data: {
    width: 150, // 设置图片的宽度
    height: 150, // 设置图片的高度
    ESP32CAM: '连接图传',
    CamStatus: 0,
    pic: "/images/ESP32CAM.png",
    mqttStatus: 0,
    mqttControl_text: '连接MQTT'
  },
  onLoad(options) {

  },
  // 图传连接控制
  ESP32CAM_control() {
    if (this.data.CamStatus == 0) {
      this.setData({
        pic: " http://192.168.212.126/mjpeg/1", // 连接ESP32CAM
        CamStatus: 1,
        ESP32CAM: '断开图传'
      })
    } else if (this.data.CamStatus == 1) {
      this.setData({
        pic: "/images/ESP32CAM.png",
        CamStatus: 0,
        ESP32CAM: '连接图传'
      })
    }
  },
  connectMQTT() {
    const options = {
      connectTimeout: 4000, // 超时时间
      reconnectPeriod: 1000, // 重连时间间隔
      clientId,
      username,
      password
    }
    // 连接MQTT服务器
    client = mqtt.connect(connectUrl, options);
    // 连接成功后触发的回调函数
    client.on('connect', () => {
      console.log('服务器连接成功')
      wx.showToast({
        title: 'MQTT连接成功',
      })
    });
    client.on('reconnect', (error) => {
      console.log('正在重连：', error)
      wx.showToast({
        title: 'MQTT正在重连',
      })
    });
    client.on('error', (error) => {
      console.log('连接失败：', error)
      wx.showToast({
        title: 'MQTT连接失败',
      })
    });
    client.on('close', function () {
      console.log('MQTT已断开连接')
      wx.showToast({
        title: 'MQTT已断开连接',
      })
    })
  },
  disconnectMQTT() {
    client.end();
    client.on('close', function () {
      console.log('MQTT已断开连接')
      wx.showToast({
        title: 'MQTT已断开连接',
      })
    })
  },
  // MQTT连接控制
  MQTTControl() {
    if (this.data.mqttStatus == 0) {
      this.connectMQTT();
      this.setData({
        mqttStatus: 1,
        mqttControl_text: '断开MQTT'
      })
    } else if (this.data.mqttStatus == 1) {
      this.disconnectMQTT()
      this.setData({
        mqttStatus: 0,
        mqttControl_text: '连接MQTT'
      })
    }
  },
  // 无人船运动控制
  up() {
    console.log('前进')
    client.publish(topic1, '{"msg":1}');
  },
  left() {
    console.log('左转')
    client.publish(topic1, '{"msg":2}');
  },
  stop() {
    console.log('停止')
    client.publish(topic1, '{"msg":0}');
  },
  right() {
    console.log('右转')
    client.publish(topic1, '{"msg":3}');
  },
  down() {
    console.log('后退')
    client.publish(topic1, '{"msg":4}');
  },
})